#include<iostream>
#include<cstdlib>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
#include<signal.h>

#define ROOT "/"
#define devnull "/dev/null"

void Daemon(bool nochdir,bool noclose)
{
    ::signal(SIGCHLD,SIG_IGN);
    ::signal(SIGPIPE,SIG_IGN);
    if(fork()>0) exit(0);//父进程退出,子进程成为守护进程
    ::setsid();//创建新的会话
    if(!nochdir) chdir(ROOT);//改变工作目录
    
    if(!noclose){
        close(0);
        close(1);
        close(2);
    }else{
        int fd = ::open(devnull,O_WRONLY);
        dup2(fd,0);
        dup2(fd,1);        
        dup2(fd,2);        
        close(fd);
    }
}